extends Spatial

# only used in editor
export(float) var strength: float = 30.0
export(float) var cycle: float = 3.0
export(float, 0.0, 1.0, 0.01) var phase: float = 0.0

onready var rigid_body: RigidBody = $RigidBody

func _ready():
	if not Engine.editor_hint:
		$EditorOnly.queue_free()

		# move upwards a little bit ???
		var dy: float = 1.2
		rigid_body.transform.origin += Vector3(0.0, dy, 0.0)
		_create_rope(rigid_body, $StaticBody, 1.8 + dy, 6.0, 0.4)

func _physics_process(delta):
	if abs(strength) > 1e-3 and cycle > 1e-3:
		phase = fmod(phase + delta / cycle, 1.0)
		var force: Vector3 = Vector3(strength * cos(2.0 * PI * phase), 0.0, 0.0)
		rigid_body.add_central_force(global_transform.basis.xform(force))

func _create_rope(obj1: PhysicsBody, obj2: PhysicsBody, y1: float, y2: float, segment_length: float):
	var num_ropes: int = round((y2 - y1) / segment_length) as int
	var ropes: Array = [obj1]
	for i in num_ropes:
		var rope: PhysicsBody = preload("res://objects/SandbagRope.tscn").instance()
		add_child(rope)
		ropes.append(rope)
		rope.transform.origin = Vector3(0.0, lerp(y1, y2, (i + 0.5) / num_ropes), 0.0)
	ropes.append(obj2)
	for i in num_ropes + 1:
		var joint: PinJoint = PinJoint.new()
		# joint.set("params/bias", 1.0)
		joint.transform.origin = Vector3(0.0, lerp(y1, y2, (i as float) / num_ropes), 0.0)
		add_child(joint)
		joint.set("nodes/node_a", joint.get_path_to(ropes[i]))
		joint.set("nodes/node_b", joint.get_path_to(ropes[i + 1]))
